package com.gy.hsim.bservice.auth;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gy.hsim.bservice.framework.bean.BaseRequest;
import com.gy.hsim.bservice.framework.bean.QueryReponse;
import com.gy.hsim.bservice.framework.bean.SystemConfig;
import com.gy.hsim.bservice.framework.enums.MessageResultEnum;
import com.gy.hsim.bservice.framework.spring.SpringUtil;
import com.gy.hsim.bservice.netAuth.service.NetAuthService;

/**
 * 
 * @ClassName: AuthFilter
 * @Description: 用户/网元鉴权filter
 * @author Lee
 * @date 2015-1-30 下午5:28:33
 */
public class AuthFilter implements Filter {

	private static final Logger log = LoggerFactory.getLogger(AuthFilter.class);

	private NetAuthService netAuthService;
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterchain) throws IOException, ServletException {
		// TODO Auto-generated method stub

		request.setCharacterEncoding("UTF-8");

		HttpServletRequest hreq = (HttpServletRequest) request;

		HttpServletResponse hresp = (HttpServletResponse) response;

		BaseRequest baseRequest = getEntityFromRequestContent(hreq);
		
		String custId = baseRequest.getCustId();
		String channelType = baseRequest.getChannelType();
		String loginToken = baseRequest.getLoginToken();
		String entResNo = baseRequest.getEntResNo();
		String imSystem = baseRequest.getImSystem();
		
		this.netAuthService = (NetAuthService)SpringUtil.getBean("netAuthService");
		
		/** 如果是im系统请求数据，则鉴权时验证imSystem的值，否则按照正常流程进行鉴权*/
		if(imSystem == null || !imSystem.equals("imSystem")){
			/** 如果是非消息引擎系统去业务服务取数据则去电商登录鉴权 ,如果是非消息引擎系统去业务服务取数据则在内部做网元鉴权*/
			if (baseRequest.getAccessId() == null
					|| baseRequest.getAccessPasswd() == null) {
				/** 如果entResNo为空，说明是消费者鉴权，否则是企业操作员鉴权*/
				if(entResNo == null){
					if (!SSOAuth.consumerAuth(custId, channelType, loginToken)) {
						
						response.setContentType("UTF-8");

						QueryReponse resp = new QueryReponse();

						resp.setRetCode(MessageResultEnum.EXEC_AUTHENTFAILD
								.getRetCode());
						resp.setMessage(MessageResultEnum.EXEC_AUTHENTFAILD
								.getMessage());
						response.setCharacterEncoding("UTF-8");
						response.getWriter().write(JSON.toJSONString(resp));
						response.getWriter().close();
						return;

					}
				} else {
					if (!SSOAuth.opratorAuth(custId, entResNo, channelType, loginToken)) {
						
						response.setContentType("UTF-8");

						QueryReponse resp = new QueryReponse();

						resp.setRetCode(MessageResultEnum.EXEC_AUTHENTFAILD
								.getRetCode());
						resp.setMessage(MessageResultEnum.EXEC_AUTHENTFAILD
								.getMessage());
						response.setCharacterEncoding("UTF-8");
						response.getWriter().write(JSON.toJSONString(resp));
						response.getWriter().close();
						return;

					}
				}				
			
			} else {
				boolean result = netAuthService.auth(baseRequest);
				if (!result) {
					response.setContentType("UTF-8");
					QueryReponse resp = new QueryReponse();
					resp.setRetCode(MessageResultEnum.EXEC_AUTHENTFAILD
							.getRetCode());
					resp.setMessage(MessageResultEnum.EXEC_AUTHENTFAILD
							.getMessage());
					response.setCharacterEncoding("UTF-8");
					response.getWriter().write(JSON.toJSONString(resp));
					response.getWriter().close();
					return;
				}
			}
		}
						
		hreq.setAttribute("object", baseRequest.getData());

		filterchain.doFilter(hreq, hresp);

	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
	}

	/**
	 * 获取json请求转换为object对象
	 * 
	 * @param request
	 * @return UserInfoRequest
	 */
	protected BaseRequest getEntityFromRequestContent(HttpServletRequest request) {

		String jsonStr = null;

		InputStream is = null;
		
		try {

			is = request.getInputStream();

			byte bytes[] = new byte[request.getContentLength()];

			is.read(bytes);

			// 表示请求的内容区数据为json数据
			jsonStr = new String(bytes, "UTF-8");

			log.info("AuthFilter.getEntityFromRequestContent() 请求消息为 ： "
					+ jsonStr);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if(is != null) {
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		BaseRequest userInfoReq = JSON.parseObject(jsonStr, BaseRequest.class);


		return userInfoReq;

	}

}
